#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <cstring>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "Thread.hpp"

using namespace ThreadModule;

int sockfd = -1;
std::string ip;
uint16_t port;
pthread_t id;

void Recv(){
    char buffer[128];
    struct sockaddr_in peer;
    socklen_t len = sizeof(peer);

    while(true){
        int s = recvfrom(sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr*)&peer, &len);
        if(s > 0){
            std::cout << s << std::endl;
        }
    }
}

void Send(){
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());
    socklen_t len = sizeof(server);
    sendto(sockfd, "inline", sizeof("inline"), 0, (struct sockaddr*)&server, len);
    while(true){
        std::cout << "Please Enter# " << std::endl;
        std::string input;
        getline(std::cin, input);
        sendto(sockfd, input.c_str(), input.size(), 0, (struct sockaddr*)&server, len);
        if(input == "QUIT"){
            pthread_cancel(id);
            break;
        }
    }

}

int main(int argc, char* argv[]){
    if(argc != 3){
        std::cerr << "Usage: " << argv[0] << "server_ip " << "server_port";
        exit(1);
    }

    ip = argv[1];
    port = std::stoi(argv[2]);

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0){
        std::cerr << "SOCKET ERROR" << std::endl;
        exit(2);
    }

    Thread Recver(Recv);
    Thread Sender(Send);

    Recver.Start();
    Sender.Start();

    id = Recver.Id();

    Recver.Join();
    Sender.Join();

    return 0;
};